package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiPlatform;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.loongtech.bi.manager.system.SysProjectManager.projectIdNameMap;

/**
 * Author: yuri
 * Description: 平台配置管理
 * Date: 14:33 2017/5/24
 */
@RestController
@Scope("prototype")
@RequestMapping("/platformconfig")
public class PlatformManagementAction {
    @Resource
    private BiPlatformManager biPlatformManager;
    @Resource
    private SysLogManager sysLogManager;
    @Resource
    private Session session;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;
    /**
     * 查询
     */
    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(EntityBiPlatform e) {
        List<EntityBiPlatform> list;
        try {
            list = biPlatformManager.searchByCriteria(e);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        if (list != null && list.size() > 0) {
            for (EntityBiPlatform entityBiPlatform : list) {
                String gameid = entityBiPlatform.getGameId();
                for (Map.Entry<String, String> entry : projectIdNameMap.entrySet()) {
                    gameid = gameid.replace(entry.getKey() + ",", entry.getValue() + ",");
                }
                entityBiPlatform.setGameName(gameid);
            }
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> add(EntityBiPlatform entity) {
        ResultData<String> res = validate(entity, true, BiPlatformManager.PLATFORM_LIST);
        if (res != null) {
            return res;
        }
        try {
            biPlatformManager.persist(entity);
            StringBuilder insertSQL = new StringBuilder("insert into bi_platform(id,gameId,name,description,updateAt) values");
            insertSQL.append("(").append("'").append(entity.getId()).append("','").append(entity.getGameId()).append("','").append(entity.getName()).append("','").append(entity.getDescription()).append("',").append(Time.currentTime()).append(")");
            String gameId = entity.getGameId();
            for (String gid : gameId.split(",")) {
                syncInfoLogManager.add(gid, insertSQL.toString());
            }
            sysLogManager.addLog(session.getUserName(), "平台配置增加成功(" + entity.getName() + ")");
            biPlatformManager.init();
            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntityBiPlatform entity) {
        ResultData<String> res = validate(entity, false, BiPlatformManager.PLATFORM_LIST);
        if (res != null) {
            return res;
        }
        try {
            EntityBiPlatform cur = biPlatformManager.get(entity.getId());
            if (cur != null) {
                biPlatformManager.merge(entity);
                StringBuilder updateSQL = new StringBuilder("update bi_platform set name = ");
                updateSQL.append("'").append(entity.getName()).append("',description = '").append(entity.getDescription()).append("',updateAt = ").append(Time.currentTime()).append(" where  id = '").append(entity.getId()).append("'");
                String gameId = entity.getGameId();
                for (String gid : gameId.split(",")) {
                    syncInfoLogManager.add(gid, updateSQL.toString());
                }
                sysLogManager.addLog(session.getUserName(), "平台配置修改成功:" + entity.getName());
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(@RequestParam String id) {
        List<EntityBiChannel> cl = BiPlatformManager.PLATFORM_CHANNELS_MAP.get(id);
        if (cl != null && cl.size() > 0) {
            return new ResultData<>(RetCode.eRPlatChannel.getErrorcode(), RetCode.eRPlatChannel.getErrorMsg());
        }
        try {
            EntityBiPlatform cur = biPlatformManager.get(id);
            if (cur != null) {
                biPlatformManager.removeById(id);
                for (String gid : cur.getGameId().split(",")) {
                    syncInfoLogManager.add(gid, "delete from bi_platform where id = '" + cur.getId() + "'");
                }
                sysLogManager.addLog(session.getUserName(), "平台配置删除成功:" + id);
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    private ResultData<String> validate(EntityBiPlatform ebp, boolean isAdd, List<EntityBiPlatform> ebpList) {
        if (ebp.getGameId() == null) {
            return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getId())) {
            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getName())) {
            return new ResultData<>(RetCode.eNotExistName.getErrorcode(), RetCode.eNotExistName.getErrorMsg());
        }
        if (isAdd) {  // 如果是添加，则ID与名称皆不能重
            for (EntityBiPlatform e : ebpList) {
                if (ebp.getId().equals(e.getId())) {
                    return new ResultData<>(RetCode.eIdExist.getErrorcode(), RetCode.eIdExist.getErrorMsg());
                }
                if (ebp.getName().equals(e.getName())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        } else {  // 如果是修改，则名称不能重
            for (EntityBiPlatform e : ebpList) {
                if (!ebp.getId().equals(e.getId()) && ebp.getName().equals(e.getName())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        }
        return null;
    }
}
